<?php
// +----------------------------------------------------------------------
// | 中犇单商户
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2021 中犇科技 All rights reserved.
// +----------------------------------------------------------------------

namespace app\api\controller\v1;

use app\api\controller\Base;
use app\goods\model\GoodsSku;
use app\user\model\Certified;
use app\user\model\Collection;
use service\ApiReturn;
use think\Db;
use app\user\model\Task as TaskModel;

/**
 * 用户扩展接口
 * @package app\api\controller\v1
 */
class UserAddons extends Base
{
    /**
     * 会员签到
     * @param array $data
     * @param array $user
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @since 2019/4/11 16:51
     */
    public function userSignin($data = [], $user = [])
    {
        //实例化签到模型
        $sign = new \app\user\model\Signin();
        $result = $sign->userSignin($user['id'], $data['type']);
        if (false === $result) {
            return ApiReturn::r(0, [], $sign->getError());
        }

        //签到成功
        if ($result['status'] == 1) {
            TaskModel::doTask($user['id'], 'firstSign');
            return ApiReturn::r(1, $this->filter($result, $this->fname), lang('已连续签到') . $result['days'] . lang('天'));
        }
        //重复签到
        if ($result['status'] == 2) {
            return ApiReturn::r(1, $this->filter($result, $this->fname), $result['msg']);
        }
    }

    /**
     * 获取签到信息
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/11 16:35
     */
    public function get_user_signin($data = [], $user = [])
    {
        
        return ApiReturn::r(1, [], lang('暂时屏蔽'));
    }


    /**
     * 会员实名认证
     * @param array $data
     * @param array $user
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/1 19:36
     */
    public function certification($data = [], $user = [])
    {
        // 启动事务
        Db::startTrans();
        try {
            $data['user_id'] = $user['id'];
            // 验证
            $result = $this->validate($data, 'user/Certified.add');
            if (true !== $result) {
                exception($result);
            }
            //同一个用户，每种认证类型，只能有一条记录
            if ($data['is_reset']) {
                //如果是重新提交，则保存资料
                $data['update_time'] = time();
                $data['status'] = 0; //待审核
                $res = Certified::where(['user_id' => $user['id'], 'auth_type' => $data['auth_type']])->update($data);
                if (!$res) {
                    exception(lang('提交认证材料失败'));
                }
            } else {
                $userCertified = Certified::where(['user_id' => $user['id'], 'auth_type' => $data['auth_type']])->find();
                if ($userCertified && $userCertified['status'] != 2) {
                    exception(lang('认证中，请勿重复提交'));
                } else {
                    if ($userCertified['user_id']) {
                        $data['status'] = 0; // 认证失败重新提交状态为待审核
                        $res = Certified::where(['user_id' => $user['id'], 'auth_type' => $data['auth_type']])->update($data);
                    } else {
                        $res = Certified::create($data);
                    }
                    if (!$res) {
                        exception(lang('提交认证材料失败'));
                    }
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return ApiReturn::r(0, [], $e->getMessage());
        }

        return ApiReturn::r(1, [], lang('提交成功'));
    }

    /**
     * 获取认证状态
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/1 20:22
     */
    public function certification_status($data = [], $user = [])
    {
        $res = Certified::where('user_id', $user['id'])->find();
        if ($res) {
            $result = $this->filter($res, $this->fname);
            return ApiReturn::r(1, $result, lang('请求成功'));
        } else {
            return ApiReturn::r(1, ['status' => 99], lang('未认证'));
        }
    }

    /**
     * 获取积分明细
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/9 10:38
     */
    public function get_score_list($data = [], $user = [])
    {
        $data['type'] = $data['type'] ?? 0;
        $data['start_time'] = $data['start_time'] ?? "";
        $data['end_time'] = $data['end_time'] ?? "";
        $data['user_id'] = $user['id'];
        $result = \app\user\model\ScoreLog::getList($data);

        if ($result) {
            return ApiReturn::r(1, $result, lang('请求成功'));
        } else {
            return ApiReturn::r(1, [], lang('暂无数据'));
        }
    }
    

    /**
     * 关注/取关
     * @param $data
     * @param $user
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @since 2019/4/9 13:55
     */
    public function follow($data = [], $user = [])
    {
        $follow = new \app\user\model\Follow();
        $user_id = $data['user_id']; //被关注人ID
        $fans_id = $user['id']; //我的ID
        if ($user_id == $fans_id) {
            return ApiReturn::r(0, '', lang('你不能自己关注自己'));
        }
        $res = $follow->isFollow($user_id, $fans_id);
        if ($res) {
            $ret = $follow->delFollow($user_id, $fans_id);
            if ($ret) {
                return ApiReturn::r(1, ['follow' => 0], lang('取消关注成功'));
            }
        } else {
            $ret = $follow->saveFollow($user_id, $fans_id);
            if ($ret) {
                return ApiReturn::r(1, ['follow' => 1], lang('关注成功'));
            }
        }
        return ApiReturn::r(0, [], lang('关注失败'));
    }

    /**
     *
     * 关注 和 粉丝列表
     * @param  $data
     * @param  $user
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhulongfei [ 242054105@qq.com ]
     * autograph  nickname avatar
     *
     */
    public function follow_attention($data = [], $user = [])
    {
        $type = $data["type"];
        //我的关注
        if ($type == 1) {
            $uid = $user['id'];
            $res = Db::name("user_follow")
                ->alias("f")
                ->field("f.id,u.head_img,u.user_nickname,f.create_time,f.fans_id,f.user_id,ui.autograph")
                ->join("user u", "f.user_id = u.id")
                ->join("user_info ui", "ui.user_id = u.id")
                ->where("f.fans_id", $uid)
                ->order("f.create_time desc")
                ->paginate()
                ->each(function ($item, $key) {
                    $item['is_follow'] = 1;
                    $item['head_img'] = get_file_url($item['head_img']);
                    return $item;
                });
        } elseif ($type == 2) {
            //我的粉丝
            $res = Db::name("user_follow")
                ->alias("f")
                ->field("f.id,u.head_img,u.user_nickname,f.create_time,f.fans_id,f.user_id,ui.autograph")
                ->join("user u", "f.fans_id = u.id")
                ->join("user_info ui", "ui.user_id = u.id")
                ->where("f.user_id", $user['id'])
                ->order("f.create_time desc")
                ->paginate()
                ->each(function ($item, $key) {
                    $item['is_follow'] = \think\Db::name('user_follow')->where(['user_id' => $item['fans_id'], 'fans_id' => $item['user_id']])->count();
                    $item['head_img'] = get_file_url($item['head_img']);
                    return $item;
                });
        }
        if ($res) {
            return ApiReturn::r(1, $res, lang('请求成功'));
        }
        return ApiReturn::r(1, [], lang('没有更多数据了'));
    }
    /**
     * 手动绑定关系
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/29 11:20
     */
    public function set_user_lastid($data = [], $user = [])
    {
        //先查询是否有推荐人
        $now_lastid = Db::name('user')->where('id', $user['id'])->value('lastid');
        if ($now_lastid) {
            return ApiReturn::r(0, [], lang('您已经有推荐人了，请勿重复绑定'));
        }
        //查询邀请码所属的用户id
        $lastid = Db::name('user_info')->where('invite_code', $data['invite_code'])->value('user_id');
        if ($lastid) {
            $res = Db::name('user')->where('id', $user['id'])->update(['lastid' => $lastid]);
            if ($res) {
                return ApiReturn::r(1, [], lang('绑定成功'));
            }
        } else {
            return ApiReturn::r(0, [], lang('未找到推荐人信息'));
        }
        return ApiReturn::r(0, [], lang('绑定失败'));
    }

    /**
     * 注销类型
     * @param array $data
     * @param array $user
     * author: php迷途小书童
     * created: 2022/1/25 16:58
     */
    public function unsetType($data = [], $user = [])
    {
        $types = Db::name("user_unset_type")
            ->field('aid,name,status')
            ->where("status", 1)
            ->select();
        return ApiReturn::r(1, $types, '请求成功');
    }
    //提交注销账户申请
    public function doUnset($data = [], $user = [])
    {
        $check = Db::name("user_unset")->where("user_id", $user["id"])->find();
        if ($check) {
            Db::name("user_unset")->where("user_id", $user["id"])->update([
                "unset_type" => $data["unset_type"],
                "unset_reason" => $data["unset_reason"],
                "mobile" => $user["mobile"],
                "status" => 0,
                "update_time" => time(),
            ]);
        } else {
            Db::name("user_unset")->insert([
                "user_id" => $user["id"],
                "unset_type" => $data["unset_type"],
                "unset_reason" => $data["unset_reason"],
                "mobile" => $user["mobile"],
                "create_time" => time(),
                "update_time" => time(),
            ]);
        }
        return ApiReturn::r(1, [], '请求成功');
    }

    //获取注销账户申请状态
    public function getUnset($data = [], $user = [])
    {
        $check = Db::name("user_unset")->where("user_id", $user["id"])->find();
        $status = $check ? $check["status"] : -1;
        return ApiReturn::r(1, $status, '请求成功');
    }
}
